package com.wn.consumer.controller;

import com.wn.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author yellow Docter
 * @date 2022 -08-23
 * @desc
 */
@RestController
@RequestMapping("consumer")
@Api(tags = "consumer 消费者进行测试..")
@Slf4j
public class UserConsumer {

    @Autowired
    private RestTemplate restTemplate;

    public static final String URL = "http://localhost:9000/user";

    @ApiOperation("通过id调用userservice,提供的服务,查询user")
    @GetMapping("{id}")
    public User findUserById(@PathVariable Integer id){

        String url = URL + "/" + id;
        log.info("url:{}",url);
        User user = restTemplate.getForObject(url, User.class);

        return user;
    }

    @ApiOperation("通过id删除user")
    @DeleteMapping("{id}")
    public String deleteUserById(@PathVariable Integer id){
        String url = URL + "/" + id;
        log.info("url:{}",url);
        restTemplate.delete(url);
        return "success 删除成功...";
    }


    @ApiOperation("通过put修改user")
    @PutMapping
    public String findUserById(@RequestBody User user){
        String url = URL ;
        log.info("url:{}",url);
        restTemplate.put(url,user);

        return "修改成功..";
    }


    @ApiOperation("通过userservice,提供的服务,添加user")
    @PostMapping
    public String addUserById(@RequestBody User user){

        String url = URL;
        log.info("url:{}",url);
//        String s = restTemplate.postForObject(url, user, String.class);

        // post实体
        // ResponseBody 返回响应结果的实体 
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, user, String.class);
        HttpStatus statusCode = stringResponseEntity.getStatusCode();
        System.out.println("statusCode = " + statusCode);
        String s = stringResponseEntity.getBody().toString();

        System.out.println("s = " + s);
        return s;
    }
}
